package com.zkc.blog.controller.admin;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zkc.blog.pojo.User;
import com.zkc.blog.service.UserService;
import com.zkc.blog.uilt.ResultEntity;

/**
 * 后台登录访问控制器
 * @author Administrator
 */
@RequestMapping("admin")
@Controller
public class LoginController {

	@Autowired
	UserService userService; 
	
	/**
	 * 前往登录页面
	 * @return
	 */
	@RequestMapping("loginPage")
	public String toLogin(){
		return "admin/loginPage";
	}
	
	/**
	 * 管理员登录后台
	 * @param name
	 * @param pwd
	 * @param session
	 * @return
	 */
	@PostMapping("/login")
	public String adminLogin(@RequestParam String username,
			@RequestParam String pwd,
			HttpSession session,
			RedirectAttributes attr){//RedirectAttributes重定向可以获取数据
		User user=userService.checkUser(username, pwd);
		if(user!=null){
			session.setAttribute("user", user);
			return "admin/admin-index";
		}
		else{
			attr.addFlashAttribute("mess", "帐号名或密码错误");
			return "redirect:/admin/";
		}
	}
	
	/**
	 * 注销
	 * @param username
	 * @param pwd
	 * @param session
	 * @param attr
	 * @return
	 */
	@GetMapping("/logout")
	public String Logout(
			HttpSession session){
		session.removeAttribute("user");
		return "redirect:/admin/loginPage";
	}
	
	/**
	 * 获取用户信息
	 */
	@ResponseBody
	@GetMapping("/getuser")
	public ResultEntity<User> getUserInfo(
			HttpSession session){
		
		User user=(User) session.getAttribute("user");
		return ResultEntity.successWithoutData(user);
	}
}
